import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:erpdisplay/Dio/base_list_moel.dart';
import 'package:erpdisplay/Dio/base_model.dart';
import 'package:erpdisplay/Dio/headers_interceptors.dart';
import 'package:erpdisplay/Dio/http_error.dart';
import 'package:erpdisplay/Dio/log_interceptor.dart';
import 'package:erpdisplay/Dio/response_interceptors.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class DioManager {
  // static const String BASE_URL = "http://192.168.8.71:8081/";
  static const String BASE_URL = "http://139.196.40.231:8084/"; //外网
  // static const String BASE_URL = "http://192.168.8.107:8084/"; //内网
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 10000;

  Dio? _dio;

  ///创建单例
  //1.私有静态实例对象
  static final DioManager _dioManager = DioManager._instance();

  //2.创建工厂方法
  factory DioManager() => _dioManager;

  //3.私有的命名式构造方法
  DioManager._instance() {
    if (_dio == null) {
      ///dio配置基本属性
      BaseOptions _options = BaseOptions(
        baseUrl: BASE_URL,
        contentType: Headers.jsonContentType,
        responseType: ResponseType.json,
        connectTimeout: const Duration(milliseconds: CONNECT_TIMEOUT),
        receiveTimeout: const Duration(milliseconds: RECEIVE_TIMEOUT),
      );
      _dio = Dio(_options);

      (_dio!.httpClientAdapter as IOHttpClientAdapter).onHttpClientCreate =
          (client) {
        // client.findProxy = (url) {
        //   return proxy;
        // };

        //Trust certificate for https proxy
        client.badCertificateCallback = (cert, host, port) {
          return true;
        };
        return client;
      };

      ///拦截器
      _dio!.interceptors
        ..add(HeadersInterceptors()) //头部打印
        ..add(LogsInterceptor()) //日志打印
        ..add(ResponseInterceptors()); //相应拦截
    }
  }
  Future request<T>(
    BuildContext context,
    NetMethod method,
    String path, {
    bool isLoading = false,
    Map<String, dynamic>? param,
    Object? formData,
    Function(T)? onSuccess,
    Function(HttpError)? onError,
  }) async {
    try {
      ///开始做网络请求
      Response response = await _dio!.request(path,
          queryParameters: param,
          data: formData,
          options: Options(method: NetMethodValues[method]));
      if (response != null) {
        ///返回数据转化成对应的model实例
        BaseModel entity = BaseModel<T>.fromJson(response.data);

        ///根据状态码处理相应的状态
        if (entity.code == 200) {
          if (onSuccess != null && entity.data != null) {
            onSuccess(entity.data);
          }
        } else {
          if (onError != null) {
            onError(HttpError(
                code: entity.code.toString(), message: entity.message));
            if (entity.code.toString() == '401') {
              Fluttertoast.showToast(
                  msg: '登录过期，请重新登录', textColor: Colors.amber);
              // Navigator.push(context, MaterialPageRoute(builder: (context) {
              //   return LoginPage();
              // }));
            }
          }
        }
      } else {
        if (onError != null) {
          onError(HttpError(code: "-1", message: "未知错误"));
        }
      }
    } on DioException catch (e) {
      ///异常拦截
      if (onError != null) {
        onError(HttpError.dioError(e));
      }
    }
  }

  // 获取列表的函数
  Future requestList<T>(
    BuildContext context,
    NetMethod method,
    String path, {
    bool isLoading = false,
    Map<String, dynamic>? param,
    Object? formData,
    Function(List<T>)? onSuccess,
    Function(HttpError)? onError,
  }) async {
    try {
      ///开始做网络请求
      Response response = await _dio!.request(path,
          queryParameters: param,
          data: formData,
          options: Options(method: NetMethodValues[method]));
      if (response != null) {
        ///返回数据转化成对应的model实例
        BaseListModel res = BaseListModel<T>.fromJson(response.data);

        ///根据状态码处理相应的状态
        if (res.code == 200) {
          if (onSuccess != null) {
            onSuccess(res.data as List<T>);
          }
        } else {
          if (onError != null) {
            onError(HttpError(code: res.code.toString(), message: res.message));
          }
        }
      } else {
        if (onError != null) {
          onError(HttpError(code: "-1", message: "未知错误"));
        }
      }
    } on DioError catch (e) {
      ///异常拦截
      if (onError != null) {
        onError(HttpError.dioError(e));
      }
    }
  }
}

enum NetMethod { GET, POST, DELETE, PUT }

const NetMethodValues = {
  NetMethod.GET: "get",
  NetMethod.POST: "post",
  NetMethod.DELETE: "delete",
  NetMethod.PUT: "put"
};
